package com.itboye.mengwu.collection;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.R.integer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.pdf.PdfDocument.Page;
import android.os.Bundle;
import android.support.v4.media.MediaBrowserCompat.MediaItem.Flags;
import android.text.InputFilter.AllCaps;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseFragment;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.login.ui.LoginActivity;
import com.itboye.mengwu.app.shopcar.swipemenulistview.SwipeMenu;
import com.itboye.mengwu.app.shopcar.swipemenulistview.SwipeMenuCreator;
import com.itboye.mengwu.app.shopcar.swipemenulistview.SwipeMenuItem;
import com.itboye.mengwu.app.shopcar.swipemenulistview.SwipeMenuListView;
import com.itboye.mengwu.app.shopcar.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.itboye.mengwu.app.ui.interfaces.LCallBack;
import com.itboye.mengwu.app.ui.main.GoodsDetailActivity;
import com.itboye.mengwu.app.ui.mymeng.DoubleParse;
import com.itboye.mengwu.app.ui.mymeng.IntegerParse;
import com.itboye.mengwu.buy.ui.QueRenDingDan;
import com.itboye.mengwu.data.model.GoodsListModel;
import com.itboye.mengwu.data.model.GoodsListModel.GoodsList;
import com.itboye.mengwu.data.model.ShopCarBean;
import com.itboye.mengwu.data.model.ShopCarBeanCopy;
import com.itboye.mengwu.data.model.WoMengGoodsListModel;
import com.itboye.mengwu.data.presenter.AddGoodsPresenter;
import com.itboye.mengwu.data.presenter.ShopCarPresenter;
import com.itboye.mengwu.data.presenter.WoMengCollectionPresenter;
import com.itboye.mengwu.widget.XListView.IXListViewListener;

/**
 * 商品收藏ItemFragment
 * 
 * @author dsawe
 * 
 */
public class CollectionConentItemFragment extends BaseFragment implements
		Observer, OnClickListener, LCallBack, IXListViewListener {

	WoMengGoodsListModel dataList = new WoMengGoodsListModel();
	// ShopCarAdapter adapter;
	SwipeMenuListView xlistView;
	private int pageNum = 1;
	ViewGroup selectedAll;
	TextView delete;
	View back;
	String p;
	TextView heji;
	View jiesuan;
	int count = 0;
	// Button btn_login;// 點擊按鈕
	// ArrayList<String> ids = new ArrayList<String>();// 多选删除
	WoMengCollectionPresenter woMengCollectionPresenter;
	private String uid;
	String flag;

	RelativeLayout topbar;
	int Page = 1;

	boolean ShangLaflag = false;

	WoMengGoodsListModel dataListTwo = new WoMengGoodsListModel();
	ColelctionContentAdapter adapter = null;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_collectioncontent;

	}

	@Override
	public void onMyActivityCreated() {
		// xlistView = (SwipeMenuListView)
		// getActivity().findViewById(R.id.xlistview);
		uid = (String) SPUtils.get(getActivity(), null, SpPublicParams.UID, "");
		Bundle bundle = getArguments();// 从activity传过来的Bundle
		if (bundle != null) {
			flag = bundle.getBoolean("flag") + "";
			if ("true".equals(flag)) {
				getView().findViewById(R.id.topbar).setVisibility(View.VISIBLE);
				getView().findViewById(R.id.selectedAll).setVisibility(
						View.VISIBLE);
				getView().findViewById(R.id.xlistView).setVisibility(
						View.VISIBLE);

			} else {
				getView().findViewById(R.id.topbar).setVisibility(View.GONE);
				getView().findViewById(R.id.selectedAll).setVisibility(
						View.GONE);

			}
		}

		IntentFilter filter = new IntentFilter("changeshopcart");
		getActivity().registerReceiver(broadcastReceiver, filter);
		xlistView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(getActivity(),
						GoodsDetailActivity.class);

				intent.putExtra("pid", dataList.getList().get(arg2).getId());
				intent.putExtra("uid", uid);
				startActivity(intent);
				// ByAlert.alert("点击了" + arg2);
			}
		});

		if (uid == "" || uid == null) {
			setInvisible();
		} else {
			setVisible();
		}
		woMengCollectionPresenter = new WoMengCollectionPresenter(this);
		showProgressDialog("数据加载中，请稍后", true);
		// woMengCollectionPresenter.queryWoMengCollectionGoods(uid, pageNo,
		// pageSize);
		woMengCollectionPresenter.queryWoMengCollectionGoods((String) SPUtils
				.get(getActivity(), null, SpPublicParams.UID, ""), Page + "",
				"10");
		setListener();
		topbar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ArrayList<String> strs = new ArrayList<String>();
				int position = 0;
				for (WoMengGoodsListModel.A a : dataList.getList()) {
					if (a.isAllSelected()) {
						Log.e("??", a.getId() + "");
						strs.add(position + "");
						position++;
					}
				}
				for (int i = 0; i < strs.size(); i++) {

					AddGoodsPresenter addGoodsPresenter = new AddGoodsPresenter(
							CollectionConentItemFragment.this);
					addGoodsPresenter.addCollection(uid, dataList.getList()
							.get(Integer.parseInt(strs.get(i))).getId(), 0);

				}
				woMengCollectionPresenter.queryWoMengCollectionGoods(
						(String) SPUtils.get(getActivity(), null,
								SpPublicParams.UID, ""), Page + "", "10");

			}
		});

		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// // create "open" item
				// SwipeMenuItem openItem = new SwipeMenuItem(
				// getApplicationContext());
				// // set item background
				// openItem.setBackground(new ColorDrawable(Color.rgb(0xC9,
				// 0xC9,
				// 0xCE)));
				// // set item width
				// openItem.setWidth(dp2px(90));
				// // set item title
				// openItem.setTitle("Open");
				// // set item title fontsize
				// openItem.setTitleSize(18);
				// // set item title font color
				// openItem.setTitleColor(Color.WHITE);
				// // add to menu
				// menu.addMenuItem(openItem);

				// create "delete" item
				SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
				// set item background
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				deleteItem.setTitle("删除");
				deleteItem.setTitleColor(Color.WHITE);
				// // set item width
				deleteItem.setWidth(dp2px(90));
				deleteItem.setTitleSize(18);
				// // set a icon
				// deleteItem.setIcon(R.drawable.ic_delete);
				// deleteItem.setBackground(R.drawable.delete_list_item_bg);
				// add to menu
				menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		xlistView.setMenuCreator(creator);
		xlistView.setXListViewListener(this);
		xlistView.setPullLoadEnable(true);
		xlistView.setPullRefreshEnable(true);
		// step 2. listener item click event
		xlistView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public void onMenuItemClick(int position, SwipeMenu menu, int index) {

				switch (index) {
				case 0:
					AddGoodsPresenter addGoodsPresenter = new AddGoodsPresenter(
							CollectionConentItemFragment.this);
					addGoodsPresenter.addCollection(uid, dataList.getList()
							.get(position).getId(), 0);
					woMengCollectionPresenter.queryWoMengCollectionGoods(
							(String) SPUtils.get(getActivity(), null,
									SpPublicParams.UID, ""), Page + "", "10");

					break;
				case 1:
					// delete
					// delete(item);
					// mAppList.remove(position);
					// mAdapter.notifyDataSetChanged();
					break;
				}
			}
		});
		// carPresenter = new ShopCarPresenter(this);
		// carPresenter.getShopcar(uid);
		delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ArrayList<String> strs = new ArrayList<String>();
				int position = 0;

				for (WoMengGoodsListModel.A a : dataList.getList()) {
					if (a.isAllSelected()) {
						Log.e("??", a.getId() + "");
						strs.add(position + "");
						position++;
					}
				}
				for (int i = 0; i < strs.size(); i++) {

					AddGoodsPresenter addGoodsPresenter = new AddGoodsPresenter(
							CollectionConentItemFragment.this);
					addGoodsPresenter.addCollection(uid, dataList.getList()
							.get(Integer.parseInt(strs.get(i))).getId(), 0);

				}
				woMengCollectionPresenter.queryWoMengCollectionGoods(
						(String) SPUtils.get(getActivity(), null,
								SpPublicParams.UID, ""), Page + "", "10");
			}
		});

		setListener();
	}

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			uid = (String) SPUtils.get(getContext(), null, SpPublicParams.UID,
					"");
			// carPresenter.getShopcar(uid);
		}
	};
	private ColelctionContentAdapter mAdapter;
	private GoodsListModel arrayDataList;

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	public void calculatePrice() {
		double sum = 0;
		int count = 0;
		// for (ShopCarBeanCopy.GetList bean : dataList.getList()) {
		// if (bean.isSelected()) {
		// count++;
		// sum = sum + IntegerParse.parse(bean.getCount(), 0)
		// * DoubleParse.parse(bean.getPrice(), 0);
		// }
		// }
		p = String.format("%.2f", sum);
		// heji.setText("￥" + p);
		// heji.setTag(p);
		// if (count == dataList.size() && count != 0) {
		//
		// selectedAll.setSelected(true);
		//
		// } else {
		// selectedAll.setSelected(false);
		//
		// }

	}

	public void setVisible() {
		// getView().findViewById(R.id.btn_login).setVisibility(View.VISIBLE);
		// getView().findViewById(R.id.topbar).setVisibility(View.VISIBLE);
		// getView().findViewById(R.id.selectedAll).setVisibility(View.VISIBLE);
		getView().findViewById(R.id.nodata).setVisibility(View.GONE);
		xlistView.setVisibility(View.VISIBLE);

	}

	public void setInvisible() {
		// getView().findViewById(R.id.btn_login).setVisibility(View.VISIBLE);
		getView().findViewById(R.id.topbar).setVisibility(View.GONE);
		getView().findViewById(R.id.selectedAll).setVisibility(View.GONE);
		xlistView.setVisibility(View.GONE);
		getView().findViewById(R.id.bottomBar).setVisibility(View.GONE);
	}

	private void setListener() {
		// TODO Auto-generated method stub
		selectedAll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				v.setSelected(!v.isSelected());
				if (v.isSelected()) {
					v.setSelected(true);
					Log.e("aaa", dataList.getList().size() + "");
					for (int i = 0; i < dataList.getList().size(); i++) {
						dataList.getList().get(i).setAllSelected(true);
						Log.e("aaa1", i + "");
					}

				} else {
					v.setSelected(false);
					for (int i = 0; i < dataList.getList().size(); i++) {
						dataList.getList().get(i).setAllSelected(false);
						Log.e("aaa1", "123");
					}

				}
				// for (WoMengGoodsListModel.A bean : dataList.getList()) {
				// bean.setAllSelected(true);
				// }

				// if (sum == dataList.getList().size()) {
				// selectedAll.setSelected(true);
				// } else if (sum == 0) {
				// selectedAll.setSelected(false);
				// }

				// notifySelectedViewState(v.isSelected());
				adapter.notifyDataSetChanged();
				calculatePrice();
			}
		});

	}

	// protected void notifySelectedViewState(boolean b) {
	// int count =dataList.getList().size();
	// for (int i = 0; i < count; i++) {
	// try {
	// View v = xlistView.getChildAt(i).findViewById(R.id.isSelected);
	// v.setSelected(b);
	//
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }
	//
	// }

	protected void queryCountAndBuy() {
		List<String> ids = new ArrayList<String>();
		List<String> counts = new ArrayList<String>();

		// for (ShopCarBeanCopy.GetList bean : dataList.getList()) {
		// ids.add(bean.getId());
		// counts.add(bean.getCount());
		// }
		// StringBuilder idsBuilder = new StringBuilder();
		// StringBuilder countsBuilder = new StringBuilder();
		//
		// if (ids.size() > 0) {
		// idsBuilder.append(ids.get(0));
		// countsBuilder.append(counts.get(0));
		// }
		//
		// for (int i = 1; i < ids.size(); i++) {
		// idsBuilder.append(",").append(ids.get(i));
		// countsBuilder.append(",").append(counts.get(i));
		// }
	}

	@SuppressWarnings({ "unchecked", "null" })
	@Override
	public void update(Observable arg0, Object date) {
		// dataList = new WoMengGoodsListModel();
		ResultEntity entity = handlerError(date);
		if (entity != null) {
			getView().findViewById(R.id.nodata).setVisibility(View.GONE);

			if (AddGoodsPresenter.AddGoodsToCollection_success.equals(entity
					.getEventType())) {
				String str = (String) entity.getData();
				ByAlert.alert(str);

			} else if (AddGoodsPresenter.AddGoodsToCollection_fail
					.equals(entity.getEventType())) {

			}

			if (WoMengCollectionPresenter.WoMengCollecteGoodsQuery_success
					.equals(entity.getEventType())) {
				try {
					dataList = (WoMengGoodsListModel) entity.getData();

					if (ShangLaflag == true) {
						dataListTwo.getList().addAll(dataList.getList());

						if (flag != null) {
							boolean biaoji;
							if ("true".equals(flag)) {
								biaoji = true;
							} else {
								biaoji = false;
							}
							// adapter = new
							// ColelctionContentAdapter(getActivity(), dataList,
							// this, this, biaoji);
							adapter.upDate2(getActivity(), dataListTwo, this,
									this, biaoji);
						} else {
							// adapter = new
							// ColelctionContentAdapter(getActivity(), dataList,
							// this, this);
							adapter.upDate(getActivity(), dataListTwo, this,
									this);
						}
						xlistView.setAdapter(adapter);

						if (dataListTwo.getList().size() == 0) {
							getView().findViewById(R.id.nodata).setVisibility(
									View.VISIBLE);
						} else {
							getView().findViewById(R.id.nodata).setVisibility(
									View.GONE);
						}

						// adapter.upDate(wodeZengSongShangPingBeanTwo,
						// wodeZengSongShangPingBeanTwo.getList().size());

						adapter.notifyDataSetChanged();
						// initGridView(wodeZengSongShangPingBeanTwo);
					} else if (ShangLaflag == false) {

						if (flag != null) {
							boolean biaoji;
							if ("true".equals(flag)) {
								biaoji = true;
							} else {
								biaoji = false;
							}
							adapter = new ColelctionContentAdapter(
									getActivity(), dataList, this, this, biaoji);
						} else {
							adapter = new ColelctionContentAdapter(
									getActivity(), dataList, this, this);
						}
						xlistView.setAdapter(adapter);

						if (dataList.getList().size() == 0) {
							getView().findViewById(R.id.nodata).setVisibility(
									View.VISIBLE);
						} else {
							getView().findViewById(R.id.nodata).setVisibility(
									View.GONE);
						}

						dataListTwo = dataList;

						if (dataList.getList().size() == 0) {
							xlistView.setVisibility(View.GONE);
						} else {
							xlistView.setVisibility(View.VISIBLE);
						}

					}

				} catch (Exception e) {

				}

				stopLoad();

			} else if (WoMengCollectionPresenter.WoMengCollectGoodsQuery_fail
					.equals(entity.getEventType())) {

			} else {

			}

		} else {
			getView().findViewById(R.id.nodata).setVisibility(View.VISIBLE);
		}

		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		// case R.id.btn_login:
		// getActivity().startActivity(new Intent(getActivity(),
		// LoginActivity.class));
		// break;
		case R.id.jiesuan:
			queryCountAndBuy();

			// Intent intent=new Intent(getActivity(),QueRenDingDan.class);
			// intent.putExtra("list", arrayDataList);
			// startActivity(intent);
			break;
		default:
			break;
		}

	}

	class ColelctionContentAdapter extends BaseAdapter {
		Context context;
		WoMengGoodsListModel list;
		CollectionConentItemFragment collectionConentItemFragment;
		Boolean flag;

		LCallBack lCallBack;

		public ColelctionContentAdapter(Context context,
				WoMengGoodsListModel list,
				CollectionConentItemFragment collectionConentItemFragment,
				LCallBack lCallBack) {
			this.context = context;
			this.list = list;
			this.collectionConentItemFragment = collectionConentItemFragment;
			this.lCallBack = lCallBack;
		}

		public ColelctionContentAdapter(Context context,
				WoMengGoodsListModel list,
				CollectionConentItemFragment collectionConentItemFragment,
				LCallBack lCallBack, Boolean flag) {
			this.context = context;
			this.list = list;
			this.collectionConentItemFragment = collectionConentItemFragment;
			this.flag = flag;
			this.lCallBack = lCallBack;
		}

		public void upDate(Context context, WoMengGoodsListModel list,
				CollectionConentItemFragment collectionConentItemFragment,
				LCallBack lCallBack) {
			this.context = context;
			this.list = list;
			this.collectionConentItemFragment = collectionConentItemFragment;
			this.lCallBack = lCallBack;
		}

		public void upDate2(Context context, WoMengGoodsListModel list,
				CollectionConentItemFragment collectionConentItemFragment,
				LCallBack lCallBack, Boolean flag) {
			this.context = context;
			this.list = list;
			this.collectionConentItemFragment = collectionConentItemFragment;
			this.flag = flag;
			this.lCallBack = lCallBack;
		}

		@Override
		public int getCount() {
			return list.getList().size();
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = View.inflate(getActivity()
						.getApplicationContext(),
						R.layout.item_collectionofcontent, null);
				holder = new ViewHolder();
				holder.isSelected = convertView.findViewById(R.id.isSelected);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.img = (ImageView) convertView.findViewById(R.id.img);
				holder.jian = (TextView) convertView.findViewById(R.id.jian);
				holder.input = (TextView) convertView.findViewById(R.id.input);
				holder.itemLayout = (RelativeLayout) convertView
						.findViewById(R.id.itemLayout);
				// holder.isSelected.setOnClickListener(new OnClickListener() {
				//
				// @Override
				// public void onClick(View v) {
				//
				// if (v.isSelected()) {
				// v.setSelected(false);
				// } else {
				// v.setSelected(true );
				// }
				// collectionConentItemFragment.calculatePrice();
				// }
				// });
				convertView.setTag(holder);
			} else {

				holder = (ViewHolder) convertView.getTag();
			}

			holder.name.setText(list.getList().get(position).getName());
			holder.isSelected.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					int sum = 0;
					Log.e("~~~", position + "");
					WoMengGoodsListModel.A bean = list.getList().get(position);

					// bean.setAllSelected(!bean.isAllSelected());
					if (bean.isAllSelected()) {
						bean.setAllSelected(false);
						v.setSelected(false);

					} else {
						bean.setAllSelected(true);
						v.setSelected(true);
						// collectionConentItemFragment.sum++;
					}

					// Log.e("!!!!", collectionConentItemFragment.sum + "");

					// if (v.isSelected()) {
					// v.setSelected(false);
					// } else {
					// v.setSelected(true);
					// }
					for (WoMengGoodsListModel.A a : list.getList()) {
						if (a.isAllSelected()) {

							sum++;
						}
					}
					Log.e("!!", sum + "");
					lCallBack.answer(sum); // 回调
					collectionConentItemFragment.calculatePrice();

				}
			});
			XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
					+ list.getList().get(position).getImg(), holder.img);// =
			// (ImageView)
			// convertView.findViewById(R.id.img);
			holder.jian.setText(list.getList().get(position).getPrice());
			holder.input.setText(list.getList().get(position).getOri_price());

			if (flag != null) {
				if (flag) {
					holder.isSelected.setVisibility(View.VISIBLE);

				} else {
					holder.isSelected.setVisibility(View.GONE);

				}
			}

			// holder.itemLayout.setOnClickListener(new OnClickListener() {
			//
			// @Override
			// public void onClick(View v) {
			// // TODO Auto-generated method stub
			// Intent intent =new Intent(getActivity(),
			// GoodsDetailFragmentActivity.class);
			// intent.putExtra("pid", list.getList().get(position).getId());
			// intent.putExtra("uid", uid);
			// startActivity(intent);
			// }
			// });

			// Log.e("-----------------------",
			// list.getList().get(position).getOriPrice()+"------------------------");
			// holder.input.setText(list.getList().get(position).getOriPrice());
			// holder.input.setText(dataList.getList().get(position).get

			if (list.getList().get(position).isAllSelected()) {

				holder.isSelected.setSelected(true);

			} else {
				holder.isSelected.setSelected(false);

				// collectionConentItemFragment.sum++;
			}

			return convertView;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return list.getList();
		}

		public class ViewHolder {
			public View isSelected;
			TextView name;
			Button swipe;
			ImageView img;
			TextView guige;

			TextView jia;
			TextView jian;
			TextView input;
			TextView txtPerce;

			RelativeLayout itemLayout;

			public View getIsSelected() {
				return isSelected;
			}

			public void setIsSelected(View isSelected) {
				this.isSelected = isSelected;
			}

		}

	}

	@Override
	public void answer(int str) {
		// TODO Auto-generated method stub
		if (str == dataList.getList().size()) {
			selectedAll.setSelected(true);
		} else {
			selectedAll.setSelected(false);
		}
	}

	@Override
	public void onRefresh() {
		ShangLaflag = false;
		Page = 1;
		showProgressDialog("数据加载中，请稍后", true);
		woMengCollectionPresenter.queryWoMengCollectionGoods((String) SPUtils
				.get(getActivity(), null, SpPublicParams.UID, ""), Page + "",
				"10");
	}

	@Override
	public void onLoadMore() {
		ShangLaflag = true;
		Page++;
		showProgressDialog("数据加载中，请稍后", true);
		woMengCollectionPresenter.queryWoMengCollectionGoods((String) SPUtils
				.get(getActivity(), null, SpPublicParams.UID, ""), Page + "",
				"10");

	}

	public void stopLoad() {
		xlistView.stopLoadMore();
		xlistView.stopRefresh();
	}

}
